package edu.wit.acl.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.wit.acl.entity.Role;
import edu.wit.acl.entity.User;
import edu.wit.acl.entity.UserRole;
import edu.wit.acl.entity.vo.UserCorpProjectVo;
import edu.wit.acl.entity.vo.UserVo;
import edu.wit.acl.mapper.RoleMapper;
import edu.wit.acl.mapper.UserRoleMapper;
import edu.wit.acl.service.RoleService;
import edu.wit.acl.service.UserService;
import edu.wit.common.annotation.Log;
import edu.wit.common.api.domain.SysUser;
import edu.wit.common.api.model.LoginUser;
import edu.wit.common.enums.BusinessType;
import edu.wit.common.exception.HgException;
import edu.wit.common.exception.ResultEnums;
import edu.wit.common.result.R;
import edu.wit.common.security.service.TokenService;
import edu.wit.common.utils.MD5;
import edu.wit.common.utils.ServletUtils;
import edu.wit.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.security.core.context.SecurityContextHolder;
//import org.springframework.security.access.prepost.PreAuthorize;
//import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2020-01-12
 */
@RestController
@RequestMapping("/admin/acl/user")
//@CrossOrigin
@Api(tags = "用户模块")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @ApiOperation(value = "获取管理用户分页列表")
    @GetMapping("{page}/{limit}/{category}")
    public R index(
            @ApiParam(name = "page", value = "当前页码", required = true)
            @PathVariable Long page,
            @ApiParam(name = "limit", value = "每页记录数", required = true)
            @PathVariable Long limit,
            @ApiParam(name = "category", value = "用户种类", required = true)
            @PathVariable Long category,
            @ApiParam(name = "courseQuery", value = "查询对象", required = false)
                    User userQueryVo) {
        Page<User> pageParam = new Page<>(page, limit);
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        if (!StringUtils.isEmpty(userQueryVo.getUsername())) {
            wrapper.like("username", userQueryVo.getUsername());
        }
        wrapper.eq("category", category);

        IPage<User> pageModel = userService.page(pageParam, wrapper);
        List<User> userList = pageModel.getRecords();
        userList.forEach(user -> {
            user.setCreateBy(userService.selectById(user.getOperatorId()).getNickName());
        });

//        System.out.println("total=====" + pageModel.getTotal());
        return R.ok().data("items", userList).data("total", pageModel.getTotal());

    }

    @ApiOperation(value = "获取管理/租户用户分页列表")
    @GetMapping("pageTenantList/{page}/{limit}/{category}/{isAdmin}")
    public R pageTenantList(
            @ApiParam(name = "page", value = "当前页码", required = true)
            @PathVariable Long page,

            @ApiParam(name = "limit", value = "每页记录数", required = true)
            @PathVariable Long limit,

            @ApiParam(name = "category", value = "用户种类", required = true)
            @PathVariable Long category,

            @ApiParam(name = "isAdmin", value = "账号类型，是否为超管账号", required = true)
            @PathVariable Long isAdmin,
            @ApiParam(name = "courseQuery", value = "查询对象", required = false)
                    User userQueryVo) {

        Page<User> pageParam = new Page<>(page, limit);
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        if (!StringUtils.isEmpty(userQueryVo.getEnterpriseName())) {
            wrapper.like("enterprise_name", userQueryVo.getEnterpriseName());
            wrapper.or().like("nick_name", userQueryVo.getEnterpriseName());
            wrapper.or().like("username",userQueryVo.getEnterpriseName());
        }

        wrapper.eq("category", category);
        if (isAdmin == 1) {
            wrapper.eq("pid", 0);
        } else {
            String username = tokenService.getLoginUserByToken().getUsername();
            User user = userService.selectByUsername(username);
            wrapper.eq("pid", user.getPid().equals("0") ? user.getId() : user.getPid());
        }
        IPage<User> pageModel = userService.page(pageParam, wrapper);
        List<User> userList = pageModel.getRecords();

        List<UserVo> userVoList = new ArrayList<>();

        userList.forEach(user -> {
            UserVo userVo = new UserVo();
            Role role = roleService.selectRoleByUserId(user.getId()).get(0);
            user.setRoleName(role.getRoleName());
            user.setCreateBy(userService.selectById(user.getOperatorId()).getNickName());
            BeanUtils.copyProperties(user,userVo);


            String companyName = "项目方";
            if (role.getCompanyId().equals("0")) {
                userVo.setCompanyName(companyName);
            } else {
                userVo.setCompanyName(roleMapper.selectCompanyNameByCompanyId(role.getCompanyId()));
            }
            userVoList.add(userVo);
        });
        return R.ok().data("items", userVoList).data("total", pageModel.getTotal());
    }


    @ApiOperation(value = "获取管理/租户用户分页列表")
    @GetMapping("pageTenantList2/{page}/{limit}/{category}/{isAdmin}")
    public R pageTenantList2(
            @ApiParam(name = "page", value = "当前页码", required = true)
            @PathVariable Long page,

            @ApiParam(name = "limit", value = "每页记录数", required = true)
            @PathVariable Long limit,

            @ApiParam(name = "category", value = "用户种类", required = true)
            @PathVariable Long category,

            @ApiParam(name = "isAdmin", value = "账号类型，是否为超管账号", required = true)
            @PathVariable Long isAdmin,
            @ApiParam(name = "courseQuery", value = "查询对象", required = false)
                    User userQueryVo) {

        Page<User> pageParam = new Page<>(page, limit);
        QueryWrapper<User> wrapper = new QueryWrapper<User>();

        wrapper.eq("category", category);

        User user = userService.selectByUsername(tokenService.getLoginUserByToken().getUsername());
        wrapper.eq("pid", user.getPid().equals("0") ? user.getId() : user.getPid());
        IPage<User> pageModel = userService.page(pageParam, wrapper);
        List<User> userList = pageModel.getRecords();
        User admin = userService.selectById(user.getPid().equals("0") ? user.getId() : user.getPid());
        userList.forEach(user2 -> {
            Role role = roleService.selectRoleByUserId(user2.getId()).get(0);
            user2.setRoleName(role.getRoleName());
            user2.setCreateBy(userService.selectById(user2.getOperatorId()).getNickName());
        });
        userList.add(admin);
        return R.ok().data("items", userList).data("total", pageModel.getTotal());
    }

    @ApiOperation(value = "获取管理/租户用户分页列表")
    @GetMapping("getTenantRoleList/{category}")
    public R getTenantRoleList(
            @ApiParam(name = "category", value = "用户种类", required = true)
            @PathVariable Long category) {
        QueryWrapper<Role> wrapper = new QueryWrapper<Role>();
        wrapper.eq("category", category);
        wrapper.eq("status","0");
        if (category == 3) {
            User user = userService.selectByUsername(tokenService.getLoginUserByToken().getUsername());
            wrapper.eq("parent_admin_id", user.getPid().equals("0") ? user.getId() : user.getPid());
        }
        List<Role> roleLists = roleService.list(wrapper);

        Map<String, Object> roleMap = new HashMap<>();
        roleMap.put("roleLists", roleLists);
        return R.ok().data(roleMap);
    }

    @ApiOperation(value = "新增管理用户")
    @PostMapping("save")
    @Log(title = "新增管理用户", businessType = BusinessType.INSERT)
    public R save(@RequestBody User user) {

        User user1 = userService.selectByUsername(user.getUsername());
        if (user1 != null) {
            throw new HgException(ResultEnums.AUTH_USER_IN_FOUND_ERROR.getCode(),"用户"+user1.getUsername() + ResultEnums.AUTH_USER_IN_FOUND_ERROR.getMsg());
        }

        User tempUser = userService.selectByUsername(tokenService.getLoginUserByToken().getUsername());
        user.setPassword(MD5.encrypt(user.getPassword()));
        user.setOperatorId(tempUser.getId());

        if (tempUser.getCategory() == 2) {
            //一定是租户管理员在进行操作
            user.setPid(tempUser.getPid().equals("0") ? tempUser.getId() : tempUser.getPid());
        }
        user.setStatus("0");
        if (user.getSalt() == null || user.getSalt() == "") {
            user.setSalt("http://39.106.84.65:9000/hg-idcard/2021/08/25/79d6a80d-88b8-45c9-b7b2-10d44f248e9f.jpeg");
        }
        userService.save(user);
        if (user.getCategory() != 1) {
            //说明不是昊广用户，其它用户是在创建用户时分配的角色，这里用自动给其分配角色
            String user_id = userService.selectByUsername(user.getUsername()).getId();
            userRoleService.remove(new QueryWrapper<UserRole>().eq("user_id", user_id));
            userRoleService.save(new UserRole().setUserId(user_id).setRoleId(user.getRoleId()));
        }

        return R.ok();
    }

    @ApiOperation(value = "修改管理用户")
    @PutMapping("update")
    @Log(title = "修改管理用户", businessType = BusinessType.UPDATE)
    public R updateById(@RequestBody User user) {

        if (!userService.selectById(user.getId()).getPassword().equals(user.getPassword())) {
            user.setPassword(MD5.encrypt(user.getPassword()));
        }

        userService.updateById(user);

        UserRole userRole = new UserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(user.getRoleId());
        userRoleService.update(userRole,new QueryWrapper<UserRole>().eq("user_id",user.getId()));

//        userRoleService.update(new UserRole().setUserId(user.getId()).setRoleId(roleService.selectByRoleName(user.getRoleName()).getId()),new QueryWrapper<UserRole>().eq("user_id",user.getId()));
        return R.ok();
    }

    @ApiOperation(value = "修改管理用户")
    @PutMapping("updateLoginIp")
    @Log(title = "修改管理用户", businessType = BusinessType.UPDATE)
    public void updateLoginIp(@RequestBody LoginUser loginUser) {
        userService.updateLastLoginIp(loginUser.getIpaddr(),loginUser.getUserid());
    }

    @ApiOperation(value = "删除管理用户")
    @DeleteMapping("remove/{id}")
    @Log(title = "删除管理用户", businessType = BusinessType.DELETE)
    public R remove(@PathVariable String id) {
        userService.removeById(id);

        //需要删除user_role表相关的角色信息
        List<Role> roles = roleService.selectRoleByUserId(id);
        if (roles.size() != 0) {
            //根据roleId和userId删除userRole
            QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
            wrapper.eq("role_id",roles.get(0).getId());
            wrapper.eq("user_id",id);
            userRoleService.remove(wrapper);
        }
        return R.ok();
    }

    @ApiOperation(value = "根据id列表删除管理用户")
    @DeleteMapping("batchRemove")
    @Log(title = "根据id列表删除管理用户", businessType = BusinessType.DELETE)
    public R batchRemove(@RequestBody List<String> idList) {
        userService.removeByIds(idList);
        return R.ok();
    }

    @ApiOperation(value = "根据用户获取角色数据")
    @GetMapping("/toAssign/{userId}")
    @Log(title = "根据用户获取角色数据", businessType = BusinessType.SELECT)
    public R toAssign(@PathVariable String userId) {
        Map<String, Object> roleMap = roleService.findRoleByUserId(userId);
        return R.ok().data(roleMap);
    }

    @ApiOperation(value = "根据用户分配角色")
    @PostMapping("/doAssign")
    public R doAssign(@RequestParam String userId, @RequestParam String[] roleId) {
        roleService.saveUserRoleRealtionShip(userId, roleId);
        return R.ok();
    }

    @ApiOperation(value = "根据用户id获取用户信息")
    @GetMapping("/get/{userId}")
    public R getById(@PathVariable String userId) {
//        System.out.println("userinfo---------------" + userService.getById(userId));
        User user = userService.getById(userId);
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user,userVo);

        String roleIdByUserId = userRoleService.selectRoleIdByUserId(userId);

        if (roleIdByUserId != null && !roleIdByUserId.isEmpty()) {
            Role role = roleService.selectByRoleId(roleIdByUserId);
            userVo.setRoleName(role.getRoleName());
            userVo.setCompanyId(role.getCompanyId());
            userVo.setRoleId(role.getId());
        }
        return R.ok().data("userinfo", userVo);
    }

    @ApiOperation(value = "根据用户username获取用户信息")
    @GetMapping("/getByUsername/{username}")
    public R getByUsername(@PathVariable String username) {
        return R.ok().data("userinfo", userService.selectByUsername(username));
    }

    @ApiOperation(value = "根据用户token获取用户信息")
    @GetMapping("/getUserinfo")
    public R getUserInfo() {
        String token = ServletUtils.getRequest().getHeader("token");
        LoginUser loginUser = tokenService.getLoginUser(token);
        User user = userService.selectByUsername(loginUser.getUsername());
        return R.ok().data("userinfo",user);
    }

    @ApiOperation(value = "根据用户username获取用户信息")
    @GetMapping("/getIdByUsername/{username}")
    public Long getIdByUsername(@PathVariable String username) {

//        return Long.parseLong(userService.selectByUsername(username).getId());
        return Long.parseLong(tokenService.getLoginUserByToken().getSysUser().getId());
    }

    @GetMapping("/changeStatus/{id}")
    public R changeStatus(@PathVariable String id) {

        User user = userService.selectById(id);
        if (user.getStatus().equals("0")) {
            user.setStatus("1");
        } else {
            user.setStatus("0");
        }
        boolean b = userService.updateById(user);
        if (b) {
            return R.ok();
        } else {
            return R.error().code(201).message("修改失败");
        }
    }

    @ApiOperation(value = "根据用户id修改用户状态")
    @PutMapping("updateUserStatusByUserId")
    @Log(title = "根据用户id修改用户状态", businessType = BusinessType.UPDATE)
    public R updateRoleStatusByRoleId(@RequestBody User user) {
        userService.updateUserStatus(user.getId(), user.getIsDeleted());
        return R.ok();
    }

    @ApiOperation(value = "获取当前用户所属劳务公司id")
    @GetMapping("/selectCompanyId")
    public R selectCompanyIdByUsername() {
        String token = ServletUtils.getRequest().getHeader("token");
        LoginUser loginUser = tokenService.getLoginUser(token);
        return R.ok().data("companyId", userService.selectCompanyIdByUsername(loginUser.getSysUser().getUsername()));
    }

    @ApiOperation(value = "根据劳务公司id查该该劳务公司下所有的用户")
    @GetMapping("/selectUsersByCompanyId/{companyId}")
    public R selectUsersByCompanyId(@PathVariable String companyId,
                                    @RequestHeader String projectId) {
        String token = ServletUtils.getRequest().getHeader("token");
        List<UserCorpProjectVo> userCompanyVos = new ArrayList<>();

        String username = tokenService.getLoginUser(token).getUsername();
        User user = userService.selectByUsername(username);

//        if (companyId.equals("0")) {
//            User user1 = new User();
//            if (!user.getPid().equals("0")) {
//                user1 = userService.selectById(user.getPid());
//            } else {
//                user1 = user;
//            }
//
//            UserCorpProjectVo vo = new UserCorpProjectVo();
//            vo.setId(user1.getId());
//            vo.setNickName(user1.getNickName());
//            vo.setCompanyId("0");
//            userCompanyVos.add(vo);
//        }


        List<UserCorpProjectVo> corpProjectVos = userService.selectUserCompanyByCompanyId(companyId, projectId);
        userCompanyVos.addAll(corpProjectVos);
        return R.ok().data("userList",userCompanyVos);
    }

    @ApiOperation(value = "获取info", httpMethod = "GET")
    @GetMapping("/info/{username}")
    public edu.wit.common.core.domain.R<LoginUser> getUserInfo(@PathVariable String username) {
        SysUser sysUser = userService.selectUserByUserName(username);
        if (StringUtils.isNull(sysUser)) {
            return edu.wit.common.core.domain.R.fail("用户名或密码错误");
        }
        // 角色集合
//        Set<String> roles = permissionService.getRolePermission(sysUser.getUserId());
        // 权限集合
//        Set<String> permissions = permissionService.getMenuPermission(sysUser.getUserId());
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
//        sysUserVo.setRoles(roles);
//        sysUserVo.setPermissions(permissions);
        return edu.wit.common.core.domain.R.ok(sysUserVo);
    }

    @ApiOperation(value = "判断用户名是否存在", httpMethod = "GET")
    @GetMapping("/usernameIsExist/{username}")
    public R usernameIsExist(@PathVariable String username) {
        return R.ok().data("exist",userService.usernameIsExist(username));
    }
}

